const db = require('../Mysql/sql')
const dayjs = require('dayjs')
const emo = require('../../static/emoji')
const JSONStream = require('JSONStream');
const fs = require('fs');
const path = require('path')

function tree(list, id = 'id', fid = 'fid') {
	if (!list) {
		return;
	}
	const map = {},
		tree = [];
	for (const item of list) {
		map[item[id]] = item;
	}
	for (const item of list) {
		const parent = map[item[fid]];

		if (parent) {
			(parent.children || (parent.children = [])).push(item);
		} else {
			tree.push(item);
		}
	}

	return tree;
}
const formattingData = (arr, group_key = 'type') => {
	// 先定义一个空对象和空数组；
	let map = {};
	let res = [];
	// 循环需要筛选的数组
	for (let i = 0; i < arr.length; i++) {
		let ai = arr[i];
		// 将需要筛选的属性的值作为新对象的键，并且判断是否已经存在
		if (!map[ai[group_key]]) {
			// 不存在的话就在map对象中创建一个属性的值作为键名，键值为空数组的新对象，并且把arr[i]放入
			map[ai[group_key]] = [ai];
		} else {
			// 如果已经存在就直接把arr[i]放入
			map[ai[group_key]].push(ai);
		}
	}
	return map;
}
const news = {
	//数据字典
	dictionary(req, res) {
		let info = req.query
		
		let sql = `select * from dictionary${info.type?` where find_in_set(type, ?)` : ''}`
		if (info.id) {
			sql = `select * from dictionary where find_in_set(type, ?) and fid='${info.id}'`
		}
		db.query(sql, [info.type], (err, results) => {
			if (err) return res.cc(err)
			let data = tree(results, 'nid', 'fid')
			let keys = Object.keys(formattingData(data))
			let arr = {}
			if(info.type == 'rule') {
				arr = data
			}else if(info.nid) {
				const i = data.find(v => v.nid == info.nid)
				data = i
			}else if(info.id){
				arr = formattingData(data)
			}else {
				for(let i in data){
					if(data[i].children) {
						arr[keys[i]] = data[i].children
					}
					
				}
			}
			
			res.send({
				status: 200,
				msg: '查询成功',
				data: info.type ? arr : data
			})
		})
	},
	//删除
	DelDictionary(req, res) {
		let sql = `delete from dictionary where nid=?`
		db.query(sql, req.body.id, (err, results) => {
			if (err) return res.cc(err)
			res.cc('删除成功', 200)
		})
	},
	//修改数据字典
	updateDictionary(req, res) {
		if (req.body.children) delete req.body.children
		const {
			id,
			...body
		} = req.body
		const sql2 = `select * from dictionary where nid=?`
		db.query(sql2, body.nid, (err2, results2) => {
			if (err2) return res.cc(err2)
			let sql = ``
			sql = results2.length ? `update dictionary set ? where id=${results2[0].id}` :
				`insert into dictionary set ?`

			db.query(sql, body, (err, results) => {
				if (err) return res.cc(err)
				if (results.affectedRows !== 1) return res.cc('修改失败')
				res.cc('修改成功', 200)
			})
		})
	},
	//表情包
	emoji(req, res) {
		let body = req.query
		let page = body.page * body.pageSize
		let pageSize = (Number(body.page) + 1) * body.pageSize
		let emoList = emo.slice(page, pageSize)
		res.send({
			stauts: 200,
			msg: '获取成功',
			total: emo.length,
			data: emoList,
			swiperSize: Math.ceil(emo.length / body.pageSize) || 1
		})
	},
	//热搜
	hotSearch(req, res) {
		let hotList = []

		// const $ = cheerio.load(res2.text)
	},
	//获取省市区街道
	getAddress(req, res) {
		let data = []
		const readable = fs.createReadStream('pca-code.json', {
			encoding: 'utf8'
		})
		const parser = JSONStream.parse("*")
		readable.pipe(parser);

		parser.on('data', (obj) => {
			data.push(obj)
		});
		parser.on('error', function(err) {
			res.cc('获取失败', -1, data)
		})
		parser.on('end', () => {
			res.cc('获取成功', 200, data)
		})
	}
}

module.exports = news